/*
 * Copyright 2009 Gal Dolber
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.user.client.ui;

/**
 * Runtime browser evaluation
 */
public class UserAgent {

	public enum Agents {
		OPERA, SAFARI, IE8, IE6, GECKO1_8, GECKO, CHROME, UNKNOWN
	}

	private static native String getUA() /*-{
											var ua = navigator.userAgent.toLowerCase();
											var makeVersion = function(result) {
											return (parseInt(result[1]) * 1000) + parseInt(result[2]);
											};

											if (ua.indexOf("opera") != -1) {
											return "opera";
											} else if (ua.indexOf("chrome") != -1) {
											return "chrome";
											} else if (ua.indexOf("webkit") != -1) {
											return "safari";
											} else if (ua.indexOf("msie") != -1) {
											if (document.documentMode >= 8) {
											return "ie8";
											} else {
											var result = /msie ([0-9]+)\.([0-9]+)/.exec(ua);
											if (result && result.length == 3) {
											var v = makeVersion(result);
											if (v >= 6000) {
											return "ie6";
											}
											}
											}
											} else if (ua.indexOf("gecko") != -1) {
											var result = /rv:([0-9]+)\.([0-9]+)/.exec(ua);
											if (result && result.length == 3) {
											if (makeVersion(result) >= 1008)
											return "gecko1_8";
											}
											return "gecko";
											}
											return "unknown";
											}-*/;

	public static Agents getUserAgent() {
		String agent = getUA();

		return (agent.equals("opera")) ? Agents.OPERA
			: (agent.equals("chrome")) ? Agents.CHROME
			: (agent.equals("safari")) ? Agents.SAFARI 
			: (agent.equals("ie6")) ? Agents.IE6
			: (agent.equals("ie8")) ? Agents.IE8 
			: (agent.equals("gecko1_8")) ? Agents.GECKO1_8 
			: (agent.equals("gecko")) ? Agents.GECKO
			: Agents.UNKNOWN;
	}

	/**
	 * @return
	 */
	public native static String getAgent() /*-{
		return navigator.userAgent.toLowerCase();
	}-*/;
}
